<!--
* @Description: 监控点配置/总监控点配置/关联公式
* @Author: yihua
* @Date: 2023/3/29 12:28
* @LastEditTime: 2023/3/29 12:28
-->
<template>
  <div class="formula-list-box">
    <div class="formula-list-title"> 设置属性：</div>
    <el-select
      class="formula-select"
      style="width: 100%;"
      v-model="value"
      multiple
      filterable
      @removeTag="removeTag"
      allow-create
      default-first-option
      :reserve-keyword="false"
      placeholder="设置属性"
      placement="top"
    >
      <el-option-group v-for="group in treeSelectOption" :key="group.label" :label="group.label">
        <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value">
          <el-checkbox v-model="item.checked" :label="item.label" size="large" @change="handleCheckItem(item)"/>
        </el-option>
      </el-option-group>
    </el-select>
    <div class="formula-list-title" style="margin-top:20px;"> 输入值属性：</div>
    <el-table :data="tableData" class="emission-table" v-if="tableData.length>0">
      <el-table-column label="" width="60">
        <template #default="scope">
          <span style="line-height:35px;vertical-align: top;">{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="" :width="350">
        <template #default="scope">
          <el-form-item  label="输入值名称">
            <el-input placeholder="输入值名称" style="width: 100%" :value="scope.row.name"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="" :width="300">
        <template #default="scope">
          <el-form-item  label="输入值类型">
            <el-select  filterable clearable placeholder="请选择"  style="width: 100%" v-model="scope.row.type" >
              <el-option v-for="it in ['手动输入','IOT','能源模块','产品模块','默认']" :key="it" :label="it" :value="it"/>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label=""  class-name="last-column">
        <template #default="scope">
          <el-form-item  label="值">
            <!-- v-model.trim="formDataState.code"-->
            <el-input placeholder="请输入值" v-model="scope.row.typeValue" :disabled="scope.row.type=='手动输入'? true :false " v-if="scope.row.type=='手动输入'|| scope.row.type=='默认'"/>

            <el-select  filterable clearable placeholder="请选择"  style="width: 100%" v-model="scope.row.typeValue" v-if="scope.row.type=='产品模块'">
              <el-option v-for="it in ['产值']" :key="it" :label="it" :value="it"/>
            </el-select>

            <el-select  filterable clearable placeholder="请选择"  style="width: 100%" v-model="scope.row.typeValue" v-if="scope.row.type=='能源模块'">
              <el-option v-for="it in muti_list" :key="it.energySourceType" :label="it.energySourceName" :value="it.energySourceType"/>
            </el-select>

            <div class="formula_container iotInput" id="4" @click="openFormula(formulaHtmlValue)" v-if="scope.row.type=='IOT'">
                <span class="formula_content">
                  <span class="formula_show"  ref="algorithmInput" v-html="formulaHtmlValue">
                  </span>
                </span>
              <el-tooltip  :content="formulaHtmlInputValue" placement="top" popper-class="space-auth-status-tip" v-if="formulaHtmlInputValue">
                <span><el-icon class="el-icon&#45;&#45;right" :size="18" style="margin-top:5px;"><Warning /></el-icon></span>
              </el-tooltip>
              <span v-else><el-icon class="el-icon--right" :size="18" style="margin-top:5px;"><Warning /></el-icon></span>
            </div>
          </el-form-item>
        </template>
      </el-table-column>
    </el-table>
    <el-empty :image-size="40" :description="'暂无数据'" v-else />
    <autoRuleFormula ref="autoRuleFormulaRef"  @changeAlgorithmInput="changeAlgorithmInput"/>
  </div>
</template>
<script setup lang="ts">
  import { reactive , defineProps, getCurrentInstance ,defineExpose , nextTick, ref ,watch } from 'vue';
  type FormInstance = InstanceType<typeof ElForm>;
  import { carbon_metrics }  from './backResMonotor.ts'
  import backResAddPoint  from './backResAddPoint.ts'
  import { delHtmlTag } from '@/utils/stringUtils';
  import autoRuleFormula from  './autoRuleFormula.vue'

  interface Props {
    boundaryNumber?:number,
    muti_list?: any// 输入值当选择能源模块时需要渲染的
  }

  const props = defineProps<Props>()
  const { boundaryNumber, muti_list } = props

  const formRules = {
    audit_comment: [
      {
        'required': true,
        'message': `请输入驳回意见`,
        'trigger': `blur`
      }, {
        'max': 140,
        'message': `长度不能超过140字`,
        'trigger': `blur`
      }
    ]
  }


  const cartory1 = carbon_metrics.filter((item:any)=> item.catalog == 1)
  const cartory2 = carbon_metrics.filter((item:any)=> item.catalog == 2)
  const cartory3 = carbon_metrics.filter((item:any)=> item.catalog == 3)
  const aggregationList = [{name:'平均值',value:'avg'},{name:'求合',value:'sum'}]
  const formCorrelateRef = ref();
  let formCorrelate = reactive({
    'code': ``,
    'formula': ``
  });


  let tableData = ref([])

  /* carbon_algorithms */
  const value = ref<string[]>([])

  let treeSelectOption = [];
  let levelOneArr = [];
  let levelTwoArr = []; // 装二级 id 的数组
  let levelTwoObjArr = []; // 装二级对象的数组

  backResAddPoint['carbon_algorithms'+ boundaryNumber].forEach((item)=>{
    // 顶级值在数组中的下标位置
    let index = levelOneArr.indexOf(item.carbonMetricLevel1.id);
    if(index == -1) {
      levelOneArr.push(item.carbonMetricLevel1.id)
      treeSelectOption.push({
        label: item.carbonMetricLevel1.name,
        id: item.carbonMetricLevel1.id,
        options:[
          {
            value: item.carbonMetricLevel2.id,
            label: item.carbonMetricLevel2.name,
            checked:false
          }
        ]
      })
      levelTwoArr.push(item.carbonMetricLevel2.id)
      levelTwoObjArr.push({
        index:0,
        id:item.carbonMetricLevel2.id,
        value:item.carbonMetricLevel2.name,
        parentName:item.carbonMetricLevel1.name,
        parentId:item.carbonMetricLevel1.id,
        childName:item.carbonMetricLevel3.name,
        childId:item.carbonMetricLevel3.id,
      })
    }else{
      // 二级值在二级数组中的下标位置
      let indexTwo = levelTwoArr.indexOf(item.carbonMetricLevel2.id);
      if(indexTwo == -1 ){
        treeSelectOption[index].options.push(
          {
            value: item.carbonMetricLevel2.id,
            label: item.carbonMetricLevel2.name,
            checked:false
          }
        )
        levelTwoArr.push( item.carbonMetricLevel2.id )
        levelTwoObjArr.push({
          index:treeSelectOption[index].options.length - 1,
          id:item.carbonMetricLevel2.id,
          value:item.carbonMetricLevel2.name,
          parentName:item.carbonMetricLevel1.name,
          parentId:item.carbonMetricLevel1.id,
          childName:item.carbonMetricLevel3.name,
          childId:item.carbonMetricLevel3.id,
        })
      }
    }
  })

  const removeTag = (e) => {
    const index = levelTwoArr.indexOf(e)
    varifyChecked(index,false)
    const tableIndex = tableData.value.findIndex(d => d.id == e)
    tableData.value.splice(tableIndex, 1);
  }


  const varifyChecked = (index:number,flag:boolean) => {
    if(index>-1){
      const firstLevelIndex = levelOneArr.indexOf(levelTwoObjArr[index].parentId);
      /*console.log('firstLevelIndex',firstLevelIndex);
      console.log(treeSelectOption[firstLevelIndex]);
      console.log('treeSelectOption[firstLevelIndex].options',index);
      console.log(treeSelectOption[firstLevelIndex].options);*/
      treeSelectOption[firstLevelIndex].options[levelTwoObjArr[index].index].checked = flag
    }
  }
  // 碳排放配置-> 设置属性 -> 下拉框的方法
  const handleCheckItem = (item :any)=>{
    // console.log(item);
    if(item.checked) {
      value.value.push(item.value)
    }else{
      const index = value.value.findIndex(d => d=== item.value);
      value.value.splice(index, 1);
      const tableIndex = tableData.value.findIndex(d => d.id == item.value)
      tableData.value.splice(tableIndex, 1);
      console.log('tableData.value',tableData.value);
    }
  }

  watch(
    () => value.value,
    (newValue:Array, oldValue:Array) => {

      let newLen = newValue.length

      // 比较新旧数组差异
      if( newLen > tableData.value.length ) { // 这种情况是新增的一个元素
        let oldLen = oldValue.length
        let flag = 0; // 找出到底新增了哪一个
        for(let i = 0 ; i<newLen; i++ ) {
          if(oldValue.indexOf(newValue[i]) == -1) {
            flag = newValue[i]
            break;
          }
        }
        // console.log('flag',flag);
        let myIndex = levelTwoArr.indexOf(flag);
        let obj = levelTwoObjArr[myIndex];
        /*console.log('myIndex',myIndex);
        console.log('levelTwoObjArr[myIndex]',levelTwoObjArr[myIndex]);*/
        tableData.value.push({
          index:tableData.value.length - 1 < 0 ? 1 : tableData.value.length+ 1,
          name: `${obj.parentName}/${obj.value}/${obj.childName}`,
          id:obj.id,
          value:obj.value,
          parentName:obj.parentName,
          parentId:obj.parentId,
          childName:obj.childName,
          childId:obj.childId,
          type:'默认'
        })
        console.log('tableData[myIndex]',tableData.value);
      }
    },
    { deep: true }
  )

  /* 此处是输入值属性 为IOT 时候需要用到的方法开始*/
  let formulaHtmlValue = ref('')
  let formulaHtmlInputValue = ref('')

  const autoRuleFormulaRef = ref(null)
  const openFormula = (row) => {
    console.log('row',row);
    autoRuleFormulaRef.value && autoRuleFormulaRef.value.open(row);
  }

  // 从子组件接收过来的值
  const changeAlgorithmInput = (e) =>{
    console.log('从子组件接收过来的值',e);
    formulaHtmlValue.value = e.value;
    formulaHtmlInputValue.value = delHtmlTag(e.value);
  }
  /* 此处是输入值属性 为IOT 时候需要用到的方法结束*/

</script>
<style scoped lang="scss">
  :deep{
    .el-empty{
      padding:0 0  20px;
    }
    .el-checkbox.el-checkbox--large{
      display: block !important;;
      width: 100% !important;
    }
    .emission-table {
      width: 100%;
      margin-bottom: 20px;
      .el-form-item{
        margin-right: 0 !important;
        margin-bottom: 0 !important;
        width: 100% !important;
      }
      .el-input {
        height:38px
      }
      .el-table__header-wrapper{
        display: none
      }
      .last-column .cell{
        padding-right: 0;
      }
    }
    .formula_container{
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 36px;
      padding: 4px 11px;
      line-height: 1.5715;
      background: #fff;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      cursor: pointer;
    }
    .formula_content {
      display: flex;
      align-items: center;
    }
    .monitoring-footer{
      position: fixed;
      bottom:0;
      left:235px;
      right:0;
      z-index: 10;
      width: auto;
    }
  }
  .formula-list-box{
    margin-top: 20px;
    .formula-list-title{
      margin-bottom: 20px;
    }
    .formula-list-btn{
      margin-top: 10px;
      margin-bottom: 15px;
    }
  }
  .formula-list {
    .formula-item-box{
      padding: 15px 40px 0px 10px;
      background: #f9f9f9;
      border-radius: 3px;
      margin-bottom: 15px;
    }
    .del-icon{
      float: right;
      margin-right: -30px;
      padding-top: 30px;
      width: 20px;
      cursor: pointer;
      color:#a5a5a5
    }
  }
</style>